// API请求配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '/api'

// 请求配置
export const requestConfig = {
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
}

// 通用请求方法
export async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
  const config = {
    ...requestConfig,
    ...options,
    headers: {
      ...requestConfig.headers,
      ...options.headers
    }
  }

  try {
    const response = await fetch(`${config.baseURL}${url}`, {
      ...config,
      body: options.body ? JSON.stringify(options.body) : undefined
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    return await response.json() as T
  } catch (error) {
    console.error('Request failed:', error)
    throw error
  }
}

// GET请求
export function get<T>(url: string, params?: Record<string, any>): Promise<T> {
  const searchParams = params ? new URLSearchParams(params).toString() : ''
  const fullUrl = searchParams ? `${url}?${searchParams}` : url
  return request<T>(fullUrl, { method: 'GET' })
}

// POST请求
export function post<T>(url: string, data?: any): Promise<T> {
  return request<T>(url, {
    method: 'POST',
    body: data
  })
}

// PUT请求
export function put<T>(url: string, data?: any): Promise<T> {
  return request<T>(url, {
    method: 'PUT',
    body: data
  })
}

// DELETE请求
export function del<T>(url: string): Promise<T> {
  return request<T>(url, { method: 'DELETE' })
}